import { IncomingMessage, ServerResponse } from "http"
import { Config } from "../interface"
import { AUTH_KEY, Cookie } from "../utils"

export const logout = (
    { login_url, with_login_search }: Pick<Config, 'login_url' | 'with_login_search'>
) => async (req: IncomingMessage, resp: ServerResponse) => {
    const query = with_login_search && await with_login_search(req)
    const { host } = req.headers
    resp.writeHead(302, {
        'Set-Cookie': Cookie.stringify(host.replace(/[^:]+/, AUTH_KEY), '', {
            expires: new Date()
        }),
        location: query || `/${login_url}`
    })
    resp.end()
}